import { useDispatch } from "react-redux";
import { Form, Button, Input, Toast } from "antd-mobile";
import { REQUIRED_RULE } from "@common/constants";
import { createAction } from "@common/utils";
import { SAGA_USER_PROFILE_MODIFY_PWD } from "@store/user-profile/saga-types";

const ModifyPwd = () => {
  const dispatch = useDispatch();
  const [form] = Form.useForm();

  const onFinish = () => {
    form
      .validateFields()
      .then(() => {
        dispatch(
          createAction(SAGA_USER_PROFILE_MODIFY_PWD, {
            oldPwd: form.getFieldValue("oldPwd"),
            newPwd: form.getFieldValue("newPwd"),
            callback: () => {
              form.resetFields();
              Toast.show({
                icon: "success",
                content: "修改成功",
                maskClickable: false,
              });
            },
          })
        );
        return;
      })
      .catch((err) => console.log(err));
  };

  const checkCfmPwd = async (_, value) => {
    if (value && value !== form.getFieldValue("newPwd")) {
      return Promise.reject("两次输入不一致!");
    }
    return Promise.resolve();
  };

  const checkPwdLength = async (_, value) => {
    if (value && value.length < 8) {
      return Promise.reject("密码长度至少8位!");
    }
    return Promise.resolve();
  };

  return (
    <Form
      form={form}
      onFinish={onFinish}
      footer={
        <Button block type="submit" color="primary" size="large">
          保存
        </Button>
      }
    >
      <Form.Header>修改密码</Form.Header>
      <Form.Item name="oldPwd" label="原密码" rules={REQUIRED_RULE}>
        <Input type="password" placeholder="请输入" />
      </Form.Item>
      <Form.Item
        name="newPwd"
        label="新密码"
        rules={[
          ...REQUIRED_RULE,
          {
            validator: (rule, value, callback) =>
              checkPwdLength(rule, value, callback),
          },
        ]}
      >
        <Input type="password" placeholder="请输入" />
      </Form.Item>
      <Form.Item
        name="cfmPwd"
        label="再次输入"
        rules={[
          ...REQUIRED_RULE,
          {
            validator: (rule, value, callback) =>
              checkPwdLength(rule, value, callback),
          },
          {
            validator: (rule, value, callback) =>
              checkCfmPwd(rule, value, callback),
          },
        ]}
      >
        <Input type="password" placeholder="请输入" />
      </Form.Item>
    </Form>
  );
};

export default ModifyPwd;
